package Java7_Concurrency_Cookbook.concurrent_collection_framework.delay_queue_delayed;

import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * DelayQueue 这个类可以存放带有激活日期的元素. 当读取列表时, 未来元素可以被忽略.<br/>
 * DelayQueue 中的存放的元素必须继承Delayed接口, 使对象成为延迟对象.<br/>
 * 当读取列表时, 未来元素虽然读取不到, 但是在queue中已经存在该元素了,
 * queue.size()可以查看存储了多少元素
 * @author lixiangke
 * @date 2017/11/23
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Event> queue = new DelayQueue();
        Thread[] threads = new Thread[5];
        for (int i = 0; i < threads.length; i++) {
            Task task = new Task(i + 1, queue);
            threads[i] = new Thread(task);
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
        System.out.println("Main: queue size is " + queue.size());
        do {
            int counter = 0;
            Event event;
            do {
                event = queue.poll();
                if (event != null) {
                    counter++;
                }
            } while (event != null);
            System.out.printf("At %s you have read %d events\n", new Date(), counter);
            TimeUnit.MILLISECONDS.sleep(500);
        } while (queue.size() > 0);
    }
}
